(function (doc, win) {
    //页面如果单独设置fontSzie=0;则不使用
    try{fontSzie}catch(err){fontSzie = 1;}
    if(fontSzie){
        var docEl = doc.documentElement,
            resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
            recalc = function () {
                var clientWidth = docEl.clientWidth;
                if (!clientWidth) return;
                docEl.style.fontSize = 100 * (clientWidth / 1080) + 'px';
            };

        if (!doc.addEventListener) return;
        win.addEventListener(resizeEvt, recalc, false);
        doc.addEventListener('DOMContentLoaded', recalc, false);
    }
})(document, window);
var global = {
    //加载动画...
    loading:function (on) {
        if(on == false){
            setTimeout(function () {
                $('body').find('.loading_cover').hide();
                localStorage.setItem('loading',false);
            },300);
        }else{
            var strVar = "";
            strVar += "<div class=\"loading_cover\"><div><div class=\"content\"><div class=\"rloader\">loading<\/div><p>加载中...<\/p><\/div><\/div><\/div>";
            $('body').append(strVar);
            localStorage.setItem('loading',true);
        }
    }
};

//判断是否是存在
var isNull = function(data){
    return (data == "" || data == undefined || data == null || data == false) ? false : true;
};

//数组操作
var arrData = {
    //序列化表单转数组
    serializeArray:function (mailAddress) {
        var tempNameArr = {};
        $.each(mailAddress, function(index, val) {
            tempNameArr[val['name']] = val['value'];
        });
        return tempNameArr;
    }
};

//get操作
var get  = {
    /**
     * 获取加密的id参数
     * @param name 名称
     * @param split 分隔符
     * @returns {*}
     */
    id:function (name,split) {
        name = name == undefined ? 'id' : name;
        split = split == undefined ? '/' : split;
        var id = get.init(name);
        if(id == '') return false;
        if(split){
            parameter = get.de(id).split(split); //挂全局
        }else{
            parameter = get.de(id); //挂全局
        }
        return parameter;
    },
    /**
     * 解密字符串
     * @param str 传入字符串
     * @returns {string}
     */
    de:function (str) {
        return base64Decode(str);
    },
    /**
     *  获取地址栏的参数
     * @param name 参数名
     * @returns {*}
     */
    init:function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        console.log(r);
        if (r != null) return decodeURI(r[2]);
        return '';
    },
    template:function (url) {
        $.ajaxSetup({async:false});
        return $.get('module/'+url+'.vue', function(data) {
            return data;
        }).responseText;
    },
    _template:function (cb) {
        return cb&&cb();
    }
};

//post操作
var set = {
    id:function (str) {
        return set.init(str);
    },
    /**
     * 加密字符串
     * @param str 传入需要加密的参数
     * @returns {*}
     */
    en:function (str) {
        return base64Encode(str);
    },
    init:function (str) {
        return base64Encode(str);
    }
};

//由于url地址中等号等会被编码
function base64Encode(input){
    var rv;
    rv = encodeURIComponent(input);
    rv = window.btoa(rv);
    rv = escape(rv);
    return rv;
}
function base64Decode(input){
    var rv;
    rv = decodeURIComponent(input);
    rv = window.atob(rv);
    rv = unescape(rv);
    return rv;
}

// 异步接口封装
var ajax = {
    post:function (url,obj,status,upjax,errprompt){
        var resObj;
        errprompt = errprompt == undefined?'连接服务器失败...':errprompt;
        $.ajaxSetup({async:false});
        urls = ajax.comm(url);
        if(upjax) urls = url;
        try{
            $(document).ajaxError(function (o, xhr, property, err) {
                throw new Error(err); //抛出异常
            });
            $.post(urls,obj,function(data, textStatus, xhr) {
                resObj = {data:data,status:textStatus,error:xhr};
                if(!status) resObj = data;
            });
            return resObj;
        }catch(err){
            console.info(err);
            layer.alert(errprompt);
            return false;
        }
    },
    get:function (url,status,upjax,errprompt){
        var resObj;
        errprompt = errprompt == undefined?'连接服务器失败':errprompt;
        $.ajaxSetup({async:false});
        if(!upjax) url = ajax.comm(url);
        try{
            $(document).ajaxError(function (o, xhr, property, err) {
                throw new Error(err);//抛出异常
            });
            $.get(url, function(data, textStatus, xhr) {
                resObj = {data:data,status:textStatus,error:xhr};
                if(!status) resObj = data;
            });
            return resObj;
        }catch(err){
            console.info(err);
            layer.msg(errprompt);
            return false;
        }
    },
    comm:function (url) {
        var app_version = isNull(app_version) == false?34000:app_version;
        var xrz = '?';
        if(url.indexOf('?') > 0) xrz = '&';
        return host.href+'/' + url + xrz + 'app_version=' + app_version;
    }
};

// 浏览器终端UA判断
var browser = {
    versions: function () {
        var u = navigator.userAgent, app = navigator.appVersion;
        return {
            mobile: !!u.match(/AppleWebKit.*Mobile.*/),      //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
            weixin: u.indexOf('MicroMessenger') > -1,
        };
    }(),
    language: (navigator.browserLanguage || navigator.language).toLowerCase()
};

// APP方法跳转
var app = {
    /**传入跳转地址配置
     * @auth  天明
     * @param conf
     */
    location:function (conf) {
       try{
           var config = {
               ios: 'haodai://www.xindaiquan.com'+conf['ios'],
               android: 'haodai://www.xindaiquan.com'+conf['android'],
               weixin:conf['weixin'],
               mobile:conf['mobile'],
               default:conf['default']
           };
           if (browser.versions.ios == true && config.ios != undefined) {
               location.href = config.ios;
           } else if(browser.versions.android == true && config.android != undefined){
               location.href = config.android;
           }else if(browser.versions.weixin ==true && config.weixin != undefined){
               location.href = config.weixin;
           }else if(browser.versions.mobile == true && config.mobile != undefined){
               location.href = config.mobile;
           }else{
               console.log(config);
               console.log(config.ios);
               location.href = config.ios;
           }
       }catch (err){
           layer.msg(JSON.stringify(err));
           console.log(err);
       }
    }
};

//防止重复提交的方法
var submitlock = {
    clicktime :'',
    submitClick:'',
    btn:function (e,promot) {
        if(this.submitClick == ''){
            promot = promot == undefined ? '提交中...':promot;
            this.submitClick = e.target.innerHTML;
            e.target.innerHTML = promot;
        }
    },
    unlock:function (e) {
        e.target.innerHTML = this.submitClick;
        this.submitClick = '';
    },
    lock : function (e,wait) {
        this.btn(e);//更改按钮文字
        wait = wait == undefined? 500 : wait;//点击间隔
        if(this.clickbagin == ''){
            this.clickbagin = new Date().getTime();
            return true;
        }else{
            if(new Date().getTime() - this.clicktime <= wait){
                e.target.innerHTML = '请稍后...';
                return false;
            }else{
                this.clicktime = new Date().getTime();
                return true;
            }
        }
    },
    /**
     *  提交中...
     * @param status 状态 true, 开始, false, 关闭
     * @param confim 提示文字
     */
    loading:function (status,confim) {
        confim = confim == undefined ? '加载中...':confim;
        status = status == undefined ? true : status;
        function addendHtml(confim) {
            var str = '<div class="loading_cover_opacity" style="display:block"><div><div class="content"><div class="opacity-cover"><div class="la-line-spin-clockwise-fade"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div><p>'+confim+'</p></div></div></div></div>';
            $('#mainview').append(str);
        }
        if(status == true){
            addendHtml(confim);
        }else if (status == false) {
            $('.loading_cover_opacity').hide();
        }else{
            addendHtml(confim);
        }
    }
};

//vue的ajax异步请求封装
http = {
    init:{},
    host:function (domin) {
        this.init.host = domin;
        return this;
    },
    data:function (data) {
        for(var x in data){
            //全局过滤undefined
            if(data[x] == undefined || data[x] == 'undefined'){
                data[x] = '';
            }
        }
        this.init.data = data;
        return this;
    },
    then:function (cb) {
        Vue.http.post(this.init.host,this.init.data).then(function (res) {
            cb(res.body) && cb(res.body);
        },function (err) {
            throw new Error('报错了亲~');
        }).catch(function (response) {
            // layer.alert('Orz...服务器连接异常');
        })
    },
    require:function (URL,FileType,ID) {
        ID = ID == undefined ? '' : ID;
        var oHead = document.getElementsByTagName('head').item(0);
        var addheadfile;
        if(FileType=="js"){
            addheadfile= document.createElement("script");
            addheadfile.type = "text/javascript";
            addheadfile.id = ID;
            addheadfile.src=URL;
        }else{
            addheadfile= document.createElement("link");
            addheadfile.type = "text/css";
            addheadfile.rel="stylesheet";
            addheadfile.rev = "stylesheet";
            addheadfile.media = "screen";
            addheadfile.id = ID;
            addheadfile.href=URL;
        }
        oHead.appendChild( addheadfile);
    }
};
/**
 * 判断数据格式
 * @type {{isNull: isDataFormat.isNull, isObj: isDataFormat.isObj, isExist: isDataFormat.isExist}}
 * by huangxin
 */
var isDataFormat = {
    //判断是否为空
    isNull:function(param){
        return (param == [] || param == "" || param == null || param == undefined) ? layer.msg("数据为空") : param;
    },
    //判断是否是对象
    isObj:function(obj){
        return (obj instanceof Object) ? layer.msg("数据不是一个对象") : obj;
    },
    //判断对象中是否存在某个属性
    isExist:function(data,config){
        return (data == config) ? data : layer.msg("数据有误");
    }
};

/**
 * 系统相关
 * @type {{die: sys.die, black50: sys.black50, setlocal: sys.setlocal, getlocal: sys.getlocal, random: sys.random, title: sys.title}}
 */
var sys = {
    /**
     * 结束运行终止
     * @param e
     * @returns {boolean}
     */
    die:function (e) {
        console.log(e);
        return false;
    },
    /**
     * 50%透明度
     * @param is 传入元素
     */
    black50:function (is) {
        if(is){
            var el = document.createElement('div');
            el.className = 'black50';
            el.id = 'black50';
            el.innerHTML = '';
            document.body.appendChild(el);
        }else{
            $('.black50').remove();
        }
    },
    /**
     * 设置缓存
     * @param name
     * @param key
     */
    setlocal:function (name,key) {},
    /**
     *  获取缓存
     * @param name
     * @returns {*}
     */
    getlocal:function (name) {
        var temp = localStorage.getItem(name);
        if(temp){
            try{
                return eval('(' + temp + ')');
            }catch(e){
                return temp;
            }
        }else{
            return false;
        }
    },
    /**
     * 获取随机数
     * @param len
     * @returns {string}
     */
    random:function (len) {
        len = len || 32;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = $chars.length;
        var pwd = '';
        for (i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    },
    /**
     * 修改页面标题,兼容ios
     * @param title
     */
    title:function (title) {
        var $body = $('body');
        document.title = title;
        var $iframe = $('<iframe style="display:none" src="/favicon.ico"></iframe>').on('load', function() {
            setTimeout(function() {
                $iframe.off('load').remove()
            },0);
        }).appendTo($body);
    }
};

/**
 * 专门匹配文章URL参数
 * @returns {Object}
 * by huangxin
 */
var getRequest = function () {
    var url = location.href; //获取url
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var stra = url.match(/.*\/(.*)(\??)/)[1];
        var str = stra.substr(8);
        strs = str.split("&");
        for(var i = 0; i < strs.length; i ++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
};


/**
 *  运动及动画相关
 * @type {{goAway: animate.goAway, getClass: animate.getClass}}
 */
animate = {
    /**
     *
     * @param $fa 父节点
     * @param $cs 子节点
     * @param $speed 运动速度
     * @param $add 速度矫正(选择器选择的class高度不准确)
     * @param $stop 是否停止
     */
    goAway:function ($fa,$cs,$speed,$add,$stop) {
        var allHeight = 0;//现在的滚动高度
        $speed = $speed == undefined ? 1500: $speed;
        $add = $add == undefined ? 0: $add;
        var 停止 = setInterval(function () {
            var height = $($fa).find($cs).height()-$add;
            allHeight = allHeight+height*-1;
            if((allHeight*-1) >= $($fa).height()){
                $($fa).append($($fa).html());
            }
            $($fa).animate({top:allHeight},500);
        },$speed);
        $stop = $stop == undefined ? false : $stop;
        if($stop) clearInterval(停止);
    },
    /**
     *  原生方式遍历节点获取class
     * @param classnames class名字
     * @returns {Array} 返回class数组
     */
    getClass:function (classnames) {
        var classobj= [];//定义数组
        var classint=0;//定义数组的下标
        var tags=document.getElementsByTagName("*");//获取HTML的所有标签
        for(var i in tags){//对标签进行遍历
            if(tags[i].nodeType==1){//判断节点类型
                if(tags[i].getAttribute("class") == classnames) {
                    classobj[classint]=tags[i];
                    classint++;
                }
            }
        }
        return classobj;//返回组成的数组
    }
};

/**
 * 微信分享相关的接口
 * @type {{init: {}, config: weixin.config, api: weixin.api, start: weixin.start}}
 */
weixin = {
    init:{},
    debug:function (debug) {
        debug = debug == undefined ? false : debug;
        this.init.debug = debug;
        return this;
    },
    config:function (data) {
        //传入的配置参数格式
        shareConfig = {
            title: '我离贷款订单只差一个你，火速来抢！',
            desc: '团购优惠价，未成团自动退款，真实用户一手单，按您工作地匹配订单', // 分享描述
            link: 'http://xdqm.haodai.com/Front-end/fight_groups/fight_groups.html?product_id=', // 分享链接
            imgUrl: 'http://interface.api.haodai.com/Public/img/H5reg/logo512.jpg', // 分享图标
            type: '', // 分享类型,music、video或link，不填默认为link
            dataUrl: '' // 如果type是music或video，则要提供数据链接，默认为空
        };
        this.init.config = data;
        return this;
    },
    api:function ($url) {
        $url = $url ==undefined ? location.href.split('#')[0] : $url;
        $.ajaxSetup({async:false});
        var $api = {},that = this;
        $.post('http://interface.api.haodai.com/home/shareWx/getshare', {
            url:$url,
            type: 'json'
        }, function(data) {
            var param = data.details;
            $api = {
                debug:that.init.debug,
                appId: param.appId, // 必填，公众号的唯一标识
                timestamp: param.timestamp, // 必填，生成签名的时间戳
                nonceStr: param.nonceStr, // 必填，生成签名的随机串
                signature: param.signature, // 必填，签名，见附录1
                jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline']
            };
        });
        this.init.api = $api;
        return this;
    },
    start:function (success,cancel,error) {
        wx.config(this.init.api);
        //分享到朋友圈
        var that = this;
        wx.ready(function() {
            wx.onMenuShareTimeline({
                title: that.init.config.title, // 分享标题
                link: that.init.config.link, // 分享链接
                imgUrl: that.init.config.imgUrl, // 分享图标
                success: function() {
                    success && success();
                },
                cancel: function() {
                    cancel && cancel();
                }
            });
            //分享给朋友
            wx.onMenuShareAppMessage({
                title: that.init.config.title, // 分享标题
                desc: that.init.config.desc, // 分享描述
                link: that.init.config.link, // 分享链接
                imgUrl: that.init.config.imgUrl, // 分享图标
                type: that.init.config.type, //分享类型,music、video或link，不填默认为link
                dataUrl: that.init.config.dataUrl,// 如果type是music或video，则要提供数据链接，默认为空
                success: function() {
                    success && success();
                },
                cancel: function() {
                    cancel && cancel();
                }
            });
            //分享到QQ
            wx.onMenuShareQQ({
                title: that.init.config.title, // 分享标题
                desc: that.init.config.desc, // 分享描述
                link: that.init.config.link, // 分享链接
                imgUrl: that.init.config.imgUrl, // 分享图标
                success: function() {
                    success && success();
                },
                cancel: function() {
                    cancel && cancel();
                }
            });
            //分享到腾讯微博
            wx.onMenuShareWeibo({
                title: that.init.config.title, // 分享标题
                link: that.init.config.link, // 分享链接
                imgUrl: that.init.config.imgUrl, // 分享图标
                success: function() {
                    success && success();
                },
                cancel: function() {
                    cancel && cancel();
                }
            });
            //分享到qq空间
            wx.onMenuShareQZone({
                title: that.init.config.title, // 分享标题
                link: that.init.config.link, // 分享链接
                imgUrl: that.init.config.imgUrl, // 分享图标
                success: function() {
                    success && success();
                },
                cancel: function() {
                    cancel && cancel();
                }
            });
            wx.error(function (res) {
                error && error(res);
            });
        });
        return this;
    },
    menu:function (status) {
        status = status == true ? status : false;
        if(status == true){
            document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
                WeixinJSBridge.call('showOptionMenu');//显示
            });
        }else {
            document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
                WeixinJSBridge.call('hideOptionMenu');//隐藏
            });
        }
        return this;
    },
    show:function () {
        console.log(this.init);
    }
};